import request from '@/util/request';
import type { ApiResponse } from '@/types/note/note';
import { Chat } from '@/components/message/ChatList.vue';
import { ChatHistoryData, Permission } from '@/components/message/chatContainer/ChatHistory.vue';
import { ChatRoleTypes } from '@/assets/chatBubble/chatBubble';


export interface OllamaRespone {
    message: string;
    sessionId: string;
}

export type SendCallback = (chunk: OllamaRespone) => void;

export const OllamaApi = {
    // 发送消息
    sendGeneralMessage: async (message?: OllamaRespone, sendCallback?: SendCallback): Promise<OllamaRespone> => {
        try {
            const decoder = new TextDecoder("utf-8");
            const encoder = new TextEncoder();
            let sessionId = "";
            const response = await request.stream("ollama/sendMessage", {
                data: message,
                onChunk: (chunk: Uint8Array) => {
                    try {
                        // 解码二进制数据为字符串
                        const textChunk = decoder.decode(chunk);

                        // 解析 JSON
                        const parsedChunk: OllamaRespone = JSON.parse(textChunk);

                        // 触发回调
                        sendCallback?.(parsedChunk);

                        // 更新 sessionId
                        sessionId ||= parsedChunk.sessionId;

                        // 重新编码为二进制，让 stream 继续拼接
                        return encoder.encode(parsedChunk.message);
                    } catch (err) {
                        console.warn("JSON 解析失败:", err);
                        return chunk; // 失败时返回原始数据，避免 stream 断流
                    }
                }
            });
            // 解码响应
            const responseMessage = decoder.decode(response);
            // 返回结果
            return { message: responseMessage, sessionId };
        } catch (error) {
            throw error;
        }
    },
    // 创建会话
    createChat: async (): Promise<ApiResponse<OllamaRespone>> => {
        try {
            const response = await request.post<ApiResponse<OllamaRespone>>('ollama/createChat');
            return response.data;
        } catch (error) {
            throw error;
        }
    },
    // 获取会话列表
    getChats: async (): Promise<Chat[]> => {
        try {
            const response = await request.post<ApiResponse<Chat[]>>('ollama/getChats');
            return response.data.data;
        } catch (error) {
            throw error;
        }
    },
    // 获取聊天记录
    getChatHistory: async (sessionId: string): Promise<ChatHistoryData[]> => {
        try {
            const response = await request.post<ApiResponse<any[]>>(
                'ollama/getChatHistory',
                { sessionId }, { timeout: 0 }
            );
            response.data.data.forEach((item: any) => {
                if(item.role === 'assistant')
                {
                    item.role = ChatRoleTypes.Others;
                    item.userId = 'assistant';
                    item.bubbleName = "saibopengke";
                }
                if(item.role === 'user')
                    item.role = ChatRoleTypes.Self;
            });
            console.log(response.data.data);
            return response.data.data;
        } catch (error) {
            throw error;
        }
    },
    getAvatar: () => {
        return avatar;
    },
    // 删除会话
    deleteChat: async (sessionId: string): Promise<boolean> => {
        try {
            const response = await request.post<{ data: boolean }>(
                'ollama/deleteChat',
                { sessionId }
            );
            return response.data.data;
        } catch (error) {
            throw error;
        }
    }
}

const avatar = ``;

